package com.lee.sshclient.plugin;

import android.util.Log;
import com.lee.sshclient.ShellClientContainer;
import com.lee.sshclient.ShellClient;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.OutputStream;

/**
 * Created by le on 2016/1/18.
 */
public class SSHClientPlugin extends CordovaPlugin {

    private ShellClientContainer shellClientContainer = new ShellClientContainer();

    @Override
    public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
        if ("connect".equals(action)) {
            String name = args.getString(0);
            String host = args.getString(1);
            int port = Integer.parseInt(args.getString(2));
            String user = args.getString(3);
            String password = args.getString(4);
            connectServer(callbackContext, name, host, port, user, password);
            return true;
        } else if("execute".equals(action)) {
            String name = args.getString(0);
            final String command = args.getString(1);
            ShellClient shellClient = shellClientContainer.getClient(name);
            if(shellClient == null) {
                callbackContext.error("连接不存在");
                return false;
            } else if(shellClient.isClosed()) {
                shellClientContainer.remove(name);
                callbackContext.error("连接已关闭");
                return false;
            }
            executeCommand(shellClient, command.trim());
            return true;
        } else if("close".equals(action)) {
            String name = args.getString(0);
            shellClientContainer.disconnect(name);
            callbackContext.success("成功关闭终端");
            return true;
        } else {
            return false;
        }
    }

    private void connectServer(final CallbackContext callbackContext, String name, String host, int port, String user, String password) {
        ShellClient shellClient = new ShellClient(user, password, host, port, new ShellOutputStream(callbackContext, "UTF-8"));
        shellClientContainer.putClient(name, shellClient);
        SSHConnectRunnable sshConnect = new SSHConnectRunnable(shellClient, callbackContext);
        cordova.getThreadPool().execute(sshConnect);
    }

    private void executeCommand(ShellClient shellClient, String command) {
        OutputStream receive = shellClient.getReceive();
        ShellOutputStream shellOutputStream = (ShellOutputStream) receive;
        if(! shellOutputStream.addCommand(command)) {
            Log.i("ExecuteCommand", "请等待上一条命令执行完成");
            shellOutputStream.writerLineToClient("请等待上一条命令执行完成");
            return ;
        }
        cordova.getThreadPool().execute(new SSHExecuteRunnable(shellClient, command));
    }
}
